package top.szhome.develop.controller;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;
import top.szhome.develop.service.DocumentService;
import top.szhome.framework.core.tools.exception.SzhomeException;
import top.szhome.framework.core.tools.support.Resp;
import top.szhome.framework.core.tools.util.DateUtil;
import top.szhome.framework.starter.db.support.SimpleController;
import top.szhome.develop.convert.DatasourceConverter;
import top.szhome.develop.dto.DatasourceDTO;
import top.szhome.develop.entity.Datasource;
import top.szhome.develop.qry.DatasourceQry;
import top.szhome.develop.service.DatasourceService;
import top.szhome.develop.vo.DatasourceVO;

import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotNull;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;
/**
 * 数据源接口实现
 *
 * @author 唐加利
 * @date 2023/08/21
 **/
@AllArgsConstructor
@RestController
@RequestMapping("/develop/datasource")
@Tag(name = "数据源接口")
public class DatasourceController extends SimpleController<DatasourceService, DatasourceConverter, DatasourceQry, DatasourceDTO, Datasource, DatasourceVO> {

    private final DocumentService documentService;

    private final DatasourceService datasourceService;

    /**
     * 生成代码，并下载zip包
     * @param id
     * @return
     */
    @Operation(summary = "导出数据源文档", description = "导出Excel格式的数据源文档")
    @GetMapping("excel/{id}")
    public void excel(@PathVariable Long id, HttpServletResponse response){
        try {
            Datasource datasource = datasourceService.getById(id);
            String time = DateUtil.now(DateUtil.FORMAT_LONG_SIMPLE);
            String file = URLEncoder.encode(String.format("%s_数据库文档_%s.xlsx", datasource.getName(), time), StandardCharsets.UTF_8.name());
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment;filename=" + file);
            documentService.excel(id, response.getOutputStream());
        } catch (IOException e) {
            throw new SzhomeException("获取响应流失败" , e);
        }
    }

    /**
     * 数据源同步表信息
     * @param ids
     * @return
     */
    @Operation(summary = "同步数据源", description = "同步数据源的表信息")
    @PostMapping("sync")
    public Resp sync(@RequestBody @Parameter(example = "9527,3561") @NotNull(message = "ID不能为空") List<Long> ids) {
        getBaseService().sync(ids);
        return Resp.success();
    }

}
